package BitManipulation;

public class _477_TotalHammingDistance {
    //solution 1:use loop
    //result:over time limited,use triple cycle
    public int totalHammingDistance_0(int[] nums) {
        int totalCount = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int tempCount = 0;
                int tempXOR = nums[i] ^ nums[j];
                for (int k = 31; k >= 0; k--) {
                    tempCount += (tempXOR >> k) & 1;
                }
                totalCount += tempCount;
            }
        }
        return totalCount;
    }

    //reference solution:count every bit,and get the result
    public int totalHammingDistance(int[] nums) {
        int totalCount = 0;
        for (int i = 0; i < 32; i++) {
            int tempCount = 0;
            for (int j = 0; j < nums.length; j++) {
                tempCount += (nums[j] >> i) & 1;
            }
            totalCount += tempCount * (nums.length - tempCount);
        }
        return totalCount;
    }
}
